package com.bsoft.wx.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bsoft.wx.constant.SystemConstans;
import com.bsoft.wx.execption.EmosExection;
import com.bsoft.wx.mapper.TbCheckinMapper;
import com.bsoft.wx.mapper.TbHolidaysMapper;
import com.bsoft.wx.mapper.TbWorkdayMapper;
import com.bsoft.wx.pojo.TbCheckin;
import com.bsoft.wx.service.TbCheckinService;
import com.bsoft.wx.service.TbCityService;
import com.bsoft.wx.service.TbFaceModelService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 签到表 服务实现类
 * </p>
 *
 * @author hdh
 * @since 2023-01-11
 */
@Service
@Scope("prototype") //线程异步执行
@Slf4j
public class TbCheckinServiceImpl extends ServiceImpl<TbCheckinMapper, TbCheckin> implements TbCheckinService {
    @Autowired
    private TbCheckinMapper tbCheckinMapper;
    @Autowired
    private SystemConstans systemConstans;
    @Autowired
    private TbHolidaysMapper tbHolidaysMapper;

    @Autowired
    private TbFaceModelService tbFaceModelService;

    @Autowired
    private TbWorkdayMapper tbWorkdayMapper;
//    @Autowired
//    private TbCheckinService tbCheckinService;

    @Autowired
    private TbCityService tbCityService;
    @Value("${emos.face.createFaceModelUrl}")
    private String createFaceModelUrl;
    @Value("${emos.face.checkinUrl}")
    private String checkinUrl;

//    public TbCheckinServiceImpl(@Lazy TbCheckinService tbCheckinService){
//        this.tbCheckinService=tbCheckinService;
//    }
    @Override
    public String validCanCheckIn(int userId, String data) {

        boolean bool_1 = tbHolidaysMapper.searchTodayIsHolidays() != null ? true : false;
        log.info("节假日" + tbHolidaysMapper.searchTodayIsHolidays());
        boolean bool_2 = tbWorkdayMapper.searchTodayIsWorkday() != null ? true : false;
        log.info("日期" + tbWorkdayMapper.searchTodayIsWorkday());
        String type = "工作日";
        if (DateUtil.date().isWeekend()) {
            type = "节假日";
        }
        if (bool_1) {
            type = "节假日";
        } else if (bool_2) {
            type = "工作日";
        }
        if (type.equals("节假日")) {
            return "节假日不需要考勤";
        } else {
            DateTime now = DateUtil.date();
            String start = DateUtil.today() + " " + systemConstans.attendanceStartTime;
            String end = DateUtil.today() + " " + systemConstans.attendanceEndTime;
            DateTime attendanceStarter = DateUtil.parse(start);
            DateTime attendanceEnd = DateUtil.parse(end);
            if (now.isBefore(attendanceStarter)) {
                return "还没上班考勤开始时间";
            } else if (now.isAfter(attendanceEnd)) {
                return "超过了上班考勤结束时间";
            } else {
                HashMap map = new HashMap();
                map.put("UserId", userId);
                map.put("date", data);
                map.put("start", start);
                map.put("end", end);
                boolean bool = tbCheckinMapper.haveCheckin(map) != null ? true : false;
                log.info("-----" + tbCheckinMapper.haveCheckin(map));
                return bool ? "今日已经考勤,不用重复考勤" : "可以考勤";
            }

        }
    }

    @Override
    public void insert(TbCheckin entity) {

    }

    @Override
    public void checkin(HashMap param) {
        Date d1 = DateUtil.date();

        Date d2 = DateUtil.parse(DateUtil.today() + " " + systemConstans.attendanceTime);
        //接收时间
        Date d3 = DateUtil.parse(DateUtil.today() + " " + systemConstans.attendanceEndTime);
        int status = 1;
        if (d1.compareTo(d2) < 0) {
            status = 1;
        } else if (d1.compareTo(d2) > 0 && d1.compareTo(d3) < 0) {
            status = 2;
        }
        int userId = (Integer) param.get("userId");
        String faceMode = tbFaceModelService.searchFaceMode(userId);

        if (faceMode == null) {
            throw new EmosExection("不存在人脸模型");
        } else {
            String path = (String) param.get("path");

            HttpRequest request = HttpUtil.createPost(checkinUrl);
            request.form("photo", FileUtil.file(path), "targetModel", faceMode);
            HttpResponse response = request.execute();
            if (response.getStatus() != 200) {
                log.info("人脸识别程序服务异常");
                throw new EmosExection("人脸识别服务异常");

            }
            String body = response.body();

            if ("无法识别出人脸".equals(body) || "照片中存在多张人脸".equals(body)) {


            } else if ("False".equals(body)) {
                throw new EmosExection("签到失败,非本人签到");
            } else if ("True".equals(body)) {
                //查询疫情风险等级

                int risk = 1; //低风险
                String city = (String) param.get("city");
                String district = (String) param.get("district");
                if (!StrUtil.isBlank(city) && !StrUtil.isBlank(district)) {
                    String code = tbCityService.serachCode(city);


                    try {

                        String url = "http://m." + code + ".bendibao.com/news/yqdengji/?qu=" + district;
                        Document document = Jsoup.connect(url).get();
                        Elements elements = document.getElementsByClass("list-content");
                        if (elements.size() > 0) {
                            Element element = elements.get(0);
                            String result = element.select("p:last-child").text();
                            if ("高风险".equals(result)) {
                                risk = 3;
                                // todo 发送告警邮件

                            } else if ("常态化防控".equals(result)) {
                                risk = 2;
                            }

                        }

                    } catch (Exception e) {
                        log.error("执行异常", e);
                        throw new EmosExection("获取风险等级失败");

                    }
                }
                //保存签到记录
                String address = (String) param.get("address");
                String country = (String) param.get("country");
                String province = (String) param.get("province");
                TbCheckin tbCheckin = new TbCheckin();
                tbCheckin.setUserId(userId);
                tbCheckin.setAddress(address);
                tbCheckin.setCountry(country);
                tbCheckin.setProvince(province);
                tbCheckin.setCity(city);
                tbCheckin.setDistrict(district);

                tbCheckin.setStatus(status);
                tbCheckin.setDate(DateUtil.today());
                tbCheckin.setCreateTime(d1);

              //  tbCheckinService.insert(tbCheckin);
            }

        }

    }
}
